package cn.yunyichina.reservation.controller.console;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.yunyichina.reservation.constant.Config;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.yunyichina.provider.framework.dubbo.service.ReservationService;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.reservation.common.ResponseEnum;
import cn.yunyichina.reservation.common.jackson.Jackson;
import cn.yunyichina.reservation.component.qiniu.QiniuBucket;
import cn.yunyichina.reservation.component.qiniu.QiniuService;
import cn.yunyichina.reservation.constant.Console;
import cn.yunyichina.reservation.constant.HttpResponse;
import cn.yunyichina.reservation.controller.BaseResponseController;
import cn.yunyichina.reservation.util.RequestUtil;
import cn.yunyichina.utils.convert.JsonUtils;

/**
 *  后台管理：项目管理
 */
@RestController
@RequestMapping("console")
public class ConsoleItemController extends BaseResponseController {

    private static final String RESERVATION_CONSOLE_ITEM_LIST = "yyt.reservation.item.list";
    private static final String RESERVATION_CONSOLE_ITEM_GET = "yyt.reservation.item.get";
    private static final String RESERVATION_CONSOLE_ITEM_ADD = "yyt.reservation.item.add";
    private static final String RESERVATION_CONSOLE_ITEM_UPDATE = "yyt.reservation.item.update";
    
    private static final String RESERVATION_CONSOLE_ITEM_STATUS_UPDATE = "yyt.reservation.item.status.update";
    private static final String RESERVATION_CONSOLE_ITEM_DEL = "yyt.reservation.item.del";
    
    @Resource
    private QiniuService qiniuService;

    @Resource
    private Properties yamlProperties;

    @GetMapping("items")
    public HttpResponse listItem(HttpServletRequest request) {
        Map<String, String> param = RequestUtil.getAllParameters(request);
        Response response = ReservationService.callHumpFromInternal(
                RESERVATION_CONSOLE_ITEM_LIST, JsonUtils.toJsonString(param)
        );
        return toHttpResponse(response);
    }

    @GetMapping("item")
    public HttpResponse getItem(HttpServletRequest request) {
        Map<String, String> param = RequestUtil.getAllParameters(request);
        Response response = ReservationService.callHumpFromInternal(
                RESERVATION_CONSOLE_ITEM_GET, JsonUtils.toJsonString(param)
        );
        return toHttpResponse(response);
    }

    @RequestMapping("addItem")
    public HttpResponse addItem(HttpServletRequest request) {
        Map<String, String> param = RequestUtil.getAllParameters(request);
        param.put("login_user", JsonUtils.toJsonString(this.getConsoleUser((String) request.getAttribute(Console.USERNAME))));
        Response response = ReservationService.callHumpFromInternal(
                RESERVATION_CONSOLE_ITEM_ADD, JsonUtils.toJsonString(param)
        );
        return toHttpResponse(response);
    }

    @RequestMapping("updateItem")
    public HttpResponse updateItem(HttpServletRequest request) {
        Map<String, String> param = RequestUtil.getAllParameters(request);
        param.put("login_user", JsonUtils.toJsonString(this.getConsoleUser((String) request.getAttribute(Console.USERNAME))));
        Response response = ReservationService.callHumpFromInternal(
                RESERVATION_CONSOLE_ITEM_UPDATE, JsonUtils.toJsonString(param)
        );
        return toHttpResponse(response);
    }
    
    @RequestMapping("delItem")
    public HttpResponse delItem(HttpServletRequest request) {
        Map<String, String> param = RequestUtil.getAllParameters(request);
        Response response = ReservationService.callHumpFromInternal(
        		RESERVATION_CONSOLE_ITEM_DEL, JsonUtils.toJsonString(param)
        );
        return toHttpResponse(response);
    }
    
    /**
     * 上架，下架
     * @param request stauts=1上架，status=0下架
     * @return
     */
    @RequestMapping("changeItemStatus")
    public HttpResponse changeItemStatus(HttpServletRequest request) {
        Map<String, String> param = RequestUtil.getAllParameters(request);
        Response response = ReservationService.callHumpFromInternal(
        		RESERVATION_CONSOLE_ITEM_STATUS_UPDATE, JsonUtils.toJsonString(param)
        );
        return toHttpResponse(response);
    }

    @RequestMapping(value = "/upload22", method = RequestMethod.POST)
    @ResponseBody
    public HttpResponse uploadItem(@RequestParam("name") String name,
                                   @RequestParam("file") MultipartFile file) {
        Response response = new Response();
        String message = "";
        String code = "0";

        String newName = name + System.currentTimeMillis();
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();

                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(newName)));
                stream.write(bytes);
                stream.close();
                message = "上传" + name + "成功";
                response.setResult(newName);
            } catch (Exception e) {
                message = "上传失败：" + e.getMessage();
                code = "6800";
            }
        } else {
            message = "请选择要上传的文件";
        }

        response.setResultCodeAndMessage(code, message);
        return toHttpResponse(response);
    }


    @PostMapping("upload")
    public HttpResponse itemDetailImageUpload(@RequestParam("file") MultipartFile file) throws IOException {
        HttpResponse httpResponse = new HttpResponse();
        if (!file.isEmpty()) {
            com.qiniu.http.Response response = qiniuService.upload(file.getBytes(), QiniuBucket.RESERVATION);
            String domain = yamlProperties.getProperty(Config.QINIU_CUSTOM_DOMAIN);
            if (response.isOK()) {
                Map<String, String> map = new HashMap<>();
                Map<String, String> bodyMap = Jackson.getBeanJsonData(response.bodyString(), Map.class);
                map.put("file_url", domain + bodyMap.get("hash"));
                httpResponse.setData(map);
            } else {
                httpResponse.failure(response.error);
            }
        } else {
            httpResponse.failure(ResponseEnum.ILLEGAL_PARAMETER.getCode(), ResponseEnum.ILLEGAL_PARAMETER.getMessage());
        }
        return httpResponse;
    }

}
